package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/export")
    public void download(HttpServletResponse response){
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=employee.xlsx");
            FileInputStream fileInputStream = new FileInputStream(new File("D:\\img\\temp.xlsx"));
            String fileName="D:\\img\\temp.xlsx";
            EasyExcel.write(fileName,Employee.class).sheet("员工数据").doWrite(employeeService.list());

            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //后台系统登录
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        if (employee==null || employee.getUsername() ==null || employee.getPassword()==null){
            return R.error("用户名和密码不能为空");
        }

        LambdaQueryWrapper<Employee> qw =new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee employeeServiceOne = employeeService.getOne(qw);

        if (employeeServiceOne==null){
            return R.error("用户名不存在");
        }

        if (employeeServiceOne.getStatus()!=1){
            return R.error("员工已禁用");
        }

        String userpassword = employee.getPassword();
        userpassword= DigestUtils.md5DigestAsHex(userpassword.getBytes());//用户输入密码加密

        String password = employeeServiceOne.getPassword();//数据库密码

        if (!userpassword.equals(password)){
            return R.error("密码错误");
        }

        session.setAttribute("loginUser",employeeServiceOne.getId());
        return R.success(employeeServiceOne);
    }

    //后台系统退出
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.removeAttribute("loginUser");
        return R.error("退出成功");
    }

    //新增员工
    @PostMapping
    public R saveUser(@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex(("123456").getBytes()));
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser((Long) session.getAttribute("loginUser"));
        employee.setUpdateUser((Long) session.getAttribute("loginUser"));*/

        employeeService.save(employee);

        return R.success("添加员工成功");
    }

    //分页查询
    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){

        IPage<Employee> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw =new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        qw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,qw);

        //return R.success(pageInfo);

        List<Employee> records = pageInfo.getRecords();
        Integer total = Math.toIntExact(pageInfo.getTotal());

        Map date=new HashMap();
        date.put("records",records);
        date.put("total",total);

        return R.success(date);
    }

    //员工的禁用和启用
    @PutMapping
    public R updateStatus(@RequestBody Employee employee){
        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) session.getAttribute("loginUser"));*/
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    //编辑员工
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee!=null){
            return R.success(employee);
        }
        return R.error("查无此人");
    }
}
